#!/bin/bash

#****************** 每个使用者需要修改 ****************#
commit_info="Rebuilt for xxx"
commit_auth="Name email"
# commit_info="Rebuilt for rust 1.69.0"
# commit_auth="Wang Guodong <gordonwwang@tencent.com>"

# git仓库的仓库域名、私人tocken、仓库所属的空间地址
gitee_username="Your_Name"
gitee_tocken="Your_Gitee_Tocken"
gitee_repoowner="Your_Repo_Owner"
# gitee_username="gordonwwang"
# gitee_tocken="xxxxx"
# gitee_repoowner="gordonwwang" // 存在和用户名不同的情况，根据具体情况配置

#******************     无需修改      ****************#
gitee_api="https://gitee.com/api/v5"
file_in=$1
file_out="pkg_name.log"
file_tmp="tmp.log"
file_success="pkg_success"

## 1. 从ocs代码仓，fork仓库并clone到本地
function fork_clone_repo()
{
    gitee_repo=$1

    # Delete personal repo if exists
    delete_result=$(curl -s -X DELETE -u "${gitee_username}:${gitee_tocken}" "${gitee_api}/repos/${gitee_repoowner}/${gitee_repo}")
    sleep 0.5

    # Fork repo
    fork_result=$(curl -s -X POST -u "${gitee_username}:${gitee_tocken}" "${gitee_api}/repos/opencloudos-stream/${gitee_repo}/forks")

    sleep 0.5
    # check Fork 
    if echo "$fork_result" | grep -q "\"path\":\"${gitee_repo}\""; then
        echo "====== Forked repository successfully.${gitee_repo} ======"
    else
        echo "###### Failed to fork repository.${gitee_repo}.$fork_result ######"
        exit 1
    fi    

    # clone repo
    clone_success=false
    for i in {1..5}; do
        sleep 1
        rm -rf $pkg_name

        git clone "https://gitee.com/${gitee_repoowner}/${gitee_repo}.git" --quiet        
        if [ $? -eq 0 ]; then
            clone_success=true
            break
        fi
    done

    if ! $clone_success; then
        echo "Failed to clone the repository after 5 attempts."
        exit 1
    fi
}

## 2. 修改spec文件，Release+1和changelog
function modi_spec()
{
    pkg_name="$1"
    # pkg_spec="${pkg_name}.spec"
    # Sometimes pkg_name! = spec_name
    pkg_spec="*.spec"

    if true ; then
        # use rpmdev-bumpspec to auto Release +1 
        # rpmdev-bumpspec -D -u "$commit_auth" -c "$commit_info" $pkg_spec
        rpmdev-bumpspec -u "$commit_auth" -c "$commit_info" $pkg_spec
    else
        # use rpmspec -P  to auto Release +1 
        # get "Release:" 
        release=$(rpmspec -P $pkg_spec | grep -E '^Release:' | awk '{print $2}' | grep -oE '^[0-9]+')

        # release +1
        new_release=$((release + 1))
        sed -i -E "s/^(Release:\s*)[0-9]+/\1$new_release/" "$pkg_spec"

        # add changelog
        week_num=$(date '+%a')
        month_num=$(date '+%b')
        date_num=$(date | awk '{print $3}')
        year_num=$(date '+%G')
        spec_version=$(rpmspec -P $pkg_spec | grep -iw "version:" | awk '{print $2}' | awk 'NR==1{print}')
        sed -i "s/%changelog/%changelog\n* $week_num $month_num $date_num $year_num $commit_auth - $spec_version-$new_release\n- $commit_info\n/g" $pkg_spec
    fi
}

## 3. commit、push本地代码到远端
function push_repo()
{
    gitee_repo=$1

    # set Git credential for git push
    git config credential.helper "store --file=.git/gitee_credentials"
    echo "https://${gitee_repoowner}:${gitee_tocken}@gitee.com" > .git/gitee_credentials

    git commit -am "$commit_info" --quiet
    git push origin master --quiet

    if [ $? -eq 0 ]; then
        echo "====== git push successful.${gitee_repo} ======"
    else
        echo "###### git push failed.${gitee_repo} ######"
        exit 1
    fi
}

## 4. 提Pull Requests
function PR_repo() {
    gitee_repo=$1

    # create PR
    pr_title="$commit_info"
    pr_body="auto release +1 by mybot"
    pr_head="${gitee_repoowner}:master"
    pr_base="master"
    pr_url="${gitee_api}/repos/opencloudos-stream/${gitee_repo}/pulls"

    pr_result=$(curl -s -X POST "$pr_url" \
        -H "Content-Type: application/json;charset=UTF-8" \
        -d '{
            "access_token": "'"${gitee_tocken}"'",
            "head": "'"${pr_head}"'",
            "base": "master",
            "title": "'"${pr_title}"'",
            "body": "'"${pr_body}"'"
            }')

    # check PR
    if echo "$pr_result" | grep -q "\"title\":\"${pr_title}\""; then
        echo "====== Created pull request successfully.${gitee_repo} ======"
    elif echo "$pr_result" | grep -q "存在相同源分支、目标分支的 Pull Request"; then
        echo "====== WARNING: A Pull Request already exists.${gitee_repo} ======"
    else
        echo "###### Failed to create pull request.$pr_result ######"
        exit 1
    fi
}

# when src_name != repo_name, replace it！
function replace_repo_name()
{
    pkg_name=$1
    repo_name=$1
    # 根据特殊 源码包名 替换为 仓库名
    case "$pkg_name" in
        R) repo_name="R-pkg" ;;
        dvd+rw-tools) repo_name="dvdplusrw-tools" ;;
        java-11-konajdk) repo_name="KonaJDK11" ;;
        java-17-konajdk) repo_name="KonaJDK17" ;;
        java-8-konajdk) repo_name="KonaJDK8" ;;
        libsigc++20) repo_name="libsigcplusplus20" ;;
        memtest86+) repo_name="memtest86plus" ;;
        perl-Text-Tabs+Wrap) repo_name="perl-Text-TabsplusWrap" ;;
        python-WSME) repo_name="python-wsme" ;;
        python-ovs) repo_name="python-openvswitch" ;;
        python-sysv_ipc) repo_name="python-sysv-ipc" ;;
        star) repo_name="star-pkg" ;;
    esac

    echo "$repo_name"
}

## 0. 各函数入口
function handle_pkgs()
{
    rm -f $file_success
    :> $file_success

    # 逐行读取 yaml 文件, 对每个软件包进行fork、clone、Release +1到spec、commit、push、提PR
    while IFS= read -r pkg_name; do
        repo_name=$(replace_repo_name "$pkg_name")
        if [ "$pkg_name" != "$repo_name" ]; then
            # highlight print warning
            echo -e "\033[1;31m [Warning: 源码包名和仓库名不一致，已根据列表替换!!!] \033[0m"
            echo $pkg_name "替换为" $repo_name
            pkg_name=$repo_name
        fi
        
        fork_clone_repo $pkg_name

        cur_patch=$PWD
        cd $pkg_name
        modi_spec $pkg_name
        push_repo
        # 如不需要提PR，请注释下行 PR_repo
        PR_repo $pkg_name
        cd $cur_patch
        rm -rf $pkg_name

        # 执行成功的，保存到file_success
        echo $pkg_name >> $file_success
        # 使用 sed 从文件中删除已处理的软件包
        sed -i "/^${pkg_name}$/d" "$file_out"
    done < "$file_out"
}

handle_pkgs
